<?php
class Request{
	// 目标手机号码
	public static $mobile = '';
	
	/*
	 * 复合请求
	 */
	public static function complexRequest($data) {
		foreach($data['list'] as $item) {
			$item['referer'] = $data['referer'];
			$item['usecookie'] = $data['cookie'];
			
			$log = isset($item['log']) ? $item['log'] : true;
			self::normalRequest($item, $log);
		}
	}
	
	/*
	 * 普通请求
	 */
	public static function normalRequest($data, $log = true) {
		$requestData = self::replace($data['data']);
		$url = self::replace($data['url']);
		
		self::sendRequest(
			$url,
			$requestData,
			@ $data['post'],
			@ $data['referer'],
			@ $data['usecookie'],
			$log
		);
	}
	
	/*
	 * 发送请求
	 */
	private static function sendRequest($url, $data, $isPost, $referer = null, $cookie = '', $log = true) {
		if(!$isPost) $url .= '?'.$data;
		
		if(empty($referer)) {
			$urlData = parse_url($url);
			$referer = $urlData['scheme'].$urlData['host'];
		}
		
		$curl = Curl::model();
		
		$cookie && $curl->cookie = $cookie;
		$result = $curl->request($url, array(
			'data'=> $data, 
			'referer'=> $referer,
			'https'=> preg_match("#^https#", $url),
			'is_post'=> true == $isPost,
			'timeout'=> 10,
			'use_cookie'=> true == $cookie
		));
		
		if(!$log) return;
		$resultArr = @ json_decode($result);
		$resultArr && $result = var_export($resultArr, true);
		
		$log = sprintf("\n time: %s \n url: %s \n data: %s \n result: %s\n ----end---- \n",
			date('Y-m-d H:i:s'), $url, var_export($data, true), $result);
		
		Helper::log($log);
	}
	
	// 变量替换
	private static function replace($string) {
		return str_replace(
			array('{$rand}', '{$mobile}', '{$millisecond}', '{$time}'),
			array(Helper::randNum(), self::$mobile, Helper::millisecond(), time()),
			$string
		);
	}
}